#!/usr/bin/perl -w
package index_fasta;

require Exporter;
use FindBin;
use lib ("$FindBin::Bin/.");
use die_error;

our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(index_fasta );

use warnings;
use strict;
#use Data::Dump qw(dump);




sub index_fasta($\@$)
{
	my ($file_name, $acc_filepos, $print_only) = @_;
	
	open_or_die(*FASTA, $file_name);

	my $has_accession	= 0;
	my $seq_begin		= 0;
	my $acc_begin		= 0;
	my $acc_len			= 0;
	my $acc_name		= 0;
	while (<FASTA>)
	{
		if (substr($_, 0, 1) eq '>') 
		{
			# minus 1 for '>', 1 for newline
			my $new_acc_len = length($_) - 2;
			my $new_acc_begin = tell(FASTA) - $new_acc_len - 1;
			#
			#	Save data for previous accession
			# 
			if ($has_accession && defined $acc_name)
			{
				# $seq_begin is the position of the first character after the '>'
				# 1 for '>', 1 for newline
				my $seq_len = $new_acc_begin - $seq_begin - 2;
				if ($seq_len > 0)
				{
					if ($print_only)
					{
						print join ("\t",  $acc_name, $acc_begin, $acc_len, $seq_begin, $seq_len), "\n", 
					}
					else
					{
						push(@$acc_filepos, [$acc_name, $acc_begin, $acc_len, $seq_begin, $seq_len]);
					}
				}
			}
			($acc_begin, $acc_len) = ($new_acc_begin, $new_acc_len);
			
			# mark to say that we have encountered an accession line
			$has_accession = 1;
			
			#
			#	Save data for current accession
			# 

			# $seq_begin is the position of the first character after the '>'
			$seq_begin = tell(FASTA);

			chomp;
			$acc_name = $_;
		}
	}

	#
	#	Save data for last accession
	# 
	if ($has_accession && defined $acc_name)
	{
		# $seq_begin is the position of the first character after the '>'
		# minus 1 for newline
		my $seq_len = tell(FASTA) - $seq_begin - 1;
		if ($seq_len > 0)
		{
			if ($print_only)
			{
				print join ("\t",  $acc_name, $acc_begin, $acc_len, $seq_begin, $seq_len), "\n", 
			}
			else
			{
				push(@$acc_filepos, [$acc_name, $acc_begin, $acc_len, $seq_begin, $seq_len]);
			}
		}

	}

	close FASTA;
	return 1;
}

sub test()
{
	my @acc_filepos;
	my $test_file_name = "test_index/ttest2.fa";
	index_fasta($test_file_name, @acc_filepos, 1);
	open_or_die(*FASTA, $test_file_name);
	for my $acc (@acc_filepos)
	{
		print join ("\t",  @$acc), "\n", 
	}
}

#test();
1;
